import axios from 'axios'
import store from '@/store'
import Router from '@/router'
import { removeToken,getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true,
  timeout: 5000
})


// axios请求拦截器
service.interceptors.request.use(
  config => {
    let token = getToken();
    if(token){
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)


//axios响应拦截器
service.interceptors.response.use(res=>{
    if (res.data.code === 0 && res.data.msg === 'NOT_LOGIN') {// 返回登录页面
        console.log('用户为登录, 直接跳转至登录页面');
        removeToken();
        Router.replace('/login');
        return res;
      } else {
        return res;
      }
    },
    
    error => {
      console.log('err' + error)
      let { message } = error;
      
      // 处理HTTP状态码
      if (error.response) {
        const status = error.response.status;
        switch (status) {
          case 401:
            // 未授权，跳转到登录页
            console.log('401未授权，跳转到登录页');
            removeToken();
            Router.replace('/login');
            message = "登录已过期，请重新登录";
            break;
          case 403:
            // 权限不足
            console.log('403权限不足');
            message = "权限不足，无法访问该资源";
            break;
          case 404:
            // 资源不存在，跳转到首页
            console.log('404资源不存在，跳转到首页');
            Router.replace('/');
            message = "请求的资源不存在";
            break;
          default:
            if (message.includes("Request failed with status code")) {
              message = "系统接口" + message.substr(message.length - 3) + "异常";
            }
            break;
        }
      } else {
        // 网络错误等其他错误
        if (message == "Network Error") {
          message = "后端接口连接异常";
        }
        else if (message.includes("timeout")) {
          message = "系统接口请求超时";
        }
      }
      
      return Promise.reject(error)

})

export default service
